import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:顺序表
 * User: LXW
 * Date: 2021-11-28
 * Time: 15:53
 */
public class MyArraylist {
    public int[] elem;
    public int size;

    public MyArraylist () {
        this.elem = new int[10];
    }
    // 打印顺序表
    public void display() {
        for (int i = 0; i < this.size; i++) {
            System.out.print(this.elem[i]+" ");
        }
        System.out.println();
    }
    // 在 pos 位置新增元素
    public void add(int pos, int data) {
        if (pos < 0 || pos > this.size) {
            System.out.println("pos位置不合法");
            return;
        }
        if (isfull()) {
            this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
        }
        for (int i = this.size-1; i >= pos  ; i--) {
            this.elem[i+1] = this.elem[i];
        }
        this.elem[pos] = data;
        this.size++;
    }
    public boolean isfull () {
        return this.size == this.elem.length;
    }
    // 判定是否包含某个元素
    public boolean contains(int toFind) {
        for (int i = 0; i < this.size; i++) {
            if (this.elem[i] == toFind) {
                return true;
            }
        }
        return false;
    }
    // 查找某个元素对应的位置,找不到返回-1
    public int search(int toFind) {
        for (int i = 0; i < this.size; i++) {
            if (this.elem[i] == toFind) {
                return i;
            }
        }
        return -1;
     }
    // 获取 pos 位置的元素
    public int getPos(int pos) {
        if (pos < 0 || pos > this.size) {
            System.out.println("pos位置不合法");
            return -1;       //这里说明一下，业务上的处理，这里不考虑  后期可以抛异常
        }
        if (isEmpty()) {
            return -1;
        }
        return this.elem[pos];
    }
    public boolean isEmpty () {
        return this.size == 0;
    }
    // 给 pos 位置的元素设为 value
    public void setPos(int pos, int value) {
        if (pos < 0 || pos >this.size) {
            System.out.println("pos位置不合法");
            return;
        }
        if (isEmpty()) {
            return;
        }
        this.elem[pos] = value;
    }
    //删除第一次出现的关键字key
    public void remove(int toRemove) {
        if (isEmpty()) {
            return;
        }
        int index = search(toRemove);
        for (int i = 0; i < this.size-1 ; i++) {
            this.elem[i] = this.elem[i+1];
        }
        this.size--;
    }
    // 获取顺序表长度
    public int size() {
        return this.size;
    }
    // 清空顺序表
    public void clear() {
        this.size = 0;
    }
}
